import Vue from 'vue'
import Router from 'vue-router'
import axios from 'axios'

const CdKeyCheck = r => require.ensure([], () => r(require('../components/Administration/CdKeyCheck.vue')), 'group-Account')
const LoginOn = r => require.ensure([], () => r(require('../components/Administration/LoginOn.vue')), 'group-LoginOn')
const LoginIndex = r => require.ensure([], () => r(require('../components/Administration/LoginIndex.vue')), 'group-LoginOn')
Vue.use(Router)

const router = new Router({
  routes: [
    { path: '/', redirect: '/LoginIndex' },
    { path: '/cdKeyCheck', component: CdKeyCheck },
    { path: '/loginOn', component: LoginOn },
    { path: '/loginIndex', component: LoginIndex }
  ],
  mode: 'history',
  linkActiveClass: 'mui-active'
})
router.beforeEach((to, from, next) => {
  if (to.path == '/sharebusiness' || to.path == '/sharenewsinformation' || to.path == '/newsinformation' || to.path == '/business' || to.path == '/sharebusiness' || to.path == '/information' || to.path == '/message' || to.path == '/cardinfo' || to.path == '/wechatlogin' || to.path == '/vipleaveup' || to.path == '/visitordata') {
    if (JSON.parse(localStorage.getItem('userInfo'))) {
      next()
    } else {
      let ua = navigator.userAgent.toLowerCase()// 获取判断用的对象
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        axios.post('api/queryUserSession').then(response => {
          if (response.data.code == 200) {
            localStorage.setItem('userInfo', JSON.stringify(response.data.object.userInfo))
            next()
          }
        })
      } else {
        next()
      }
    }
  } else {
    next()
  }
})

router.afterEach((to, from) => {
  const u = navigator.userAgent.toLowerCase()
  if (u.indexOf('like mac os x') < 0 || u.match(/MicroMessenger/i) != 'micromessenger') return
  if (to.path !== global.location.pathname) {
    location.assign(to.fullPath)
  }
})

export default router
